import { listenFromTopic, Options } from "@nodejs/mq"
import { responseFromBuffer } from "./proto"
import { isErrorMessage, isResponseMessage, isSendToMessage, isSendToRoomMessage } from "@core/types"
import { WebSocket } from "ws"
import { parseJSON } from "@tools/core"

export function listenWsResponseQueueV2(uuid: string, rootProto: protobuf.Root, ws: WebSocket, options: Options.AssertQueue = {
    exclusive: true
}) {
    return listenFromTopic(`response.topic`, `response.queue.${uuid}`, `response.${uuid}`, async (msg, channel) => {
        const response = responseFromBuffer(rootProto, msg.content)
        if (isErrorMessage(response)) {
            const payload = response.payload
            if (payload.reqid === (ws as any).uuid) { 
                
            }
            ws.send(JSON.stringify({ type: response.type, message: payload.message, stack: payload.stack, data: parseJSON(payload.data.toString()) }))
            channel.ack(msg)
            return;
        }
        if (isSendToMessage(response)) {
            const payload = response.payload
            ws.send(payload.data.toString())
            channel.ack(msg)
            return;
        }
        // 群发
        if (isSendToRoomMessage(response)) {
            const payload = response.payload
            // 判断是否已经发送过了
            ws.send(payload.data.toString())
            channel.ack(msg)
            return;
        }
        if (isResponseMessage(response)) {
            const payload = response.payload
            ws.send(payload.data.toString())
            channel.ack(msg)
            return;
        }
    }, options)
}